import { Request } from './utils/util.js'

App({
  onLaunch: function () {

    wx.getSystemInfo({
      success: res => {
        this.systemInfo = res
      }
    })

    // 登录
    wx.login({
      success: res => {
        let request = new Request()
        request.post('login', res => {
          if(res.success){
            this.globalData.isLogin = true
            let token = res.data.token
            wx.setStorage({key : 'token', data : token})
            this.getUserInfo()
          }
        }, {code : res.code})
      }
    })
  },


  getUserInfo () {
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: data => {
              let request = new Request()
              let params = {
                encryptedData: data.encryptedData,
                iv: data.iv,
                rawData: data.rawData,
                signature: data.signature
              }

              request.post('userinfo', res => { }, params)

              this.globalData.userInfo = { nickname: data.userInfo.nickName, avatar: data.userInfo.avatarUrl, sex: data.userInfo.gender }
              wx.setStorage({
                key: 'userinfo',
                data: this.globalData.userInfo,
              })
            }
          })
        } else {
          wx.navigateTo({
            url: '/pages/auth/index'
          })
        }
      }
    })
  },

  systemInfo : null,
  
  globalData: {
    userInfo: null,
    city : null,
    isLogin : false
  }
})